#! /bin/bash

#  This script is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2 as
#  published by the Free Software Foundation.
#
#  See the COPYING and AUTHORS files for more details.

# Read in library functions
if [ "$(type -t patch_file_name)" != function ]
then
	if ! [ -r $CMDPATH/scripts/patchfns ]
	then
		echo "Cannot read library $CMDPATH/scripts/patchfns" >&2
		exit 1
	fi
	. $CMDPATH/scripts/patchfns
fi

usage()
{
	printf $"Usage: quilt import [-f] [-p num] [-n patch] patchfile ...\n"
	if [ x$1 = x-h ]
	then
		printf $"
Import external patches.

-p num
	Number of directory levels to strip when applying (default=1)

-n patch
	Patch filename to use inside quilt. This option can only be
	used when importing a single patch.

-f	Overwite/update existing patches.
"
		exit 0
	else
		exit 1
	fi
}

options=`getopt -o fn:p:h -- "$@"`

if [ $? -ne 0 ]
then
        usage
fi

eval set -- "$options"

while true
do
        case "$1" in
        -n)
		opt_patch=${2#$QUILT_PATCHES/}
		shift 2 ;;
	-p)
		opt_strip=$2
		shift 2 ;;
	-f)
		opt_force=1
		shift ;;
	-h)
		usage -h ;;
        --)
                shift
		break ;;
        esac
done

if [ $# -gt 1 -a -n "$opt_patch" ]
then
	printf $"Option \`-n' can only be used when importing a single patch\n" >&2
	exit 1
fi

[ -n "$opt_strip" ] && patch_args="-p$opt_strip"

status=
for patch_file in "$@"
do
	if [ -n "$opt_patch" ]
	then
		patch=$opt_patch
	else
		patch=${patch_file##*/}
	fi

	if is_applied $patch
	then
		printf $"Patch %s is applied\n" "$patch" >&2
		exit 1
	fi

	if [ -e "$QUILT_PATCHES/$patch" ]
	then
		if [ -z "$opt_force" ]
		then
			printf $"Patch %s exists. Replace with -f.\n" \
			       "$(print_patch $patch)" >&2
			exit 1
		fi
		printf $"Replacing patch %s with new version\n" \
		       "$(print_patch $patch)" >&2
	else
		printf $"Importing patch %s (stored as %s)\n" \
		       "$(print_patch $patch_file)" \
		       "$(print_patch $patch)"
	fi
	dest=$QUILT_PATCHES/$patch
	mkdir -p "${dest%/*}"
	if ! cp "$patch_file" "$dest"
	then
		printf $"Failed to import patch %s\n" "$(print_patch $patch)" >&2
		status=1
	fi

	if ! patch_in_series $patch &&
	   ! insert_in_series $patch "$patch_args"
	then
		printf $"Failed to insert patch %s into file series\n" \
		       "$(print_patch $patch)" >&2
		exit 1
	fi

	rm -rf $QUILT_PC/$patch
done

exit $status
### Local Variables:
### mode: shell-script
### End:
# vim:filetype=sh
